<template>
  <section
    class="file-upload-wrapper"
    :class="{'selected': fileList.length}"
  >
    <div v-if="fileList.length && !view" class="file-content" v-for="(item, index) in fileList" :key="item.name">
      <a style="padding-right: 10px;">{{item.name}}</a>
      <span v-if="item.progress !== 100">上传进度{{item.progress}}%</span>
      <span v-if="item.progress === 100">上传成功！</span>
      <!-- <span class="el-icon-close" @click="deleteFile(index)"></span> -->
    </div>
    <div v-if="cloneValue.length" class="file-content border-bottom" v-for="(item, index) in cloneValue" :key="item.name">
      <a>{{item.fileName}}</a>
    </div>
    <div class="file-select" v-if="!view">
      <div id="video_container" class="video_container">
        <a>{{fileList.length ? '重新上传' : '选择附件'}}</a>
        <input type="file" ref="inputFile" id="selectfiles">
      </div>
      <!--<a id="postFiles" href="javascript:void(0);" class="containeBtn" style="position: relative; z-index: 1;">-->
        <!--上传-->
      <!--</a>-->
    </div>

  </section>
</template>

<script>
  import {Progress} from 'element-ui'
  import Plupload from 'plupload'
  import Crypto from '../../common/upload/crypto'
  import Base64 from '../../common/upload/base64'
  export default {
    data () {
      return {
        selected: true,
        fileName: '',
        file: '',
        fileList: [],
        cloneValue: this.value,
        progress: 0,
        fileValue: []
      }
    },
    props: {
      name: String,
      accept: {
        type: String,
        default: 'image/gif,image/jpeg,image/jpg,image/png,image/svg,application/pdf'
      },
      max: [Number, String],
      multiple: Boolean,
      value: Array,
      maxSize: {
        type: [Number, String],
        default: 1024
      },
      customeType: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      value () {
        this.cloneValue = this.value
      }
    },
    components: {
      ElProgress: Progress
    },
    computed: {
      view () {
        return this.cloneValue.length > 0
      }
    },
    methods: {
      resetData () {
        this.fileList = []
      },
      returnData () {
        return this.fileValue
      },
      init () {
        let that = this
        let limit = this.$localStorage.get(this.$const.COOKIE.KEY_OSS)
        let uploadData = JSON.parse(Base64.decode(limit))
        let accessid = uploadData.accessKeyId
        let accesskey = uploadData.accessKeySecret
        let host = uploadData.endpoint.split('//')[0] + '//' + uploadData.inputBucket + '.' + uploadData.endpoint.split('//')[1]
        let host2 = uploadData.endpoint.split('//')[0] + '//' + uploadData.bucketName + '.' + uploadData.endpoint.split('//')[1]
        let gDirname = '' // product_video newbanker-pic activity_video
        let gObjectName = ''
        let gObjectNameType = 'local_name'
        let policyText = {
          'expiration': '2020-01-01T12:00:00.000Z', // 设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
          'conditions': [
            ['content-length-range', 0, 1048576000] // 设置上传文件的大小限制
          ]
        }
        let policyBase64 = Base64.encode(JSON.stringify(policyText))
        let message = policyBase64
        let bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {asBytes: true})
        let signature = Crypto.util.bytesToBase64(bytes)
        function randomString (len) {
          len = len || 32
          var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
          var maxPos = chars.length
          var pwd = ''
          for (let i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos))
          }
          return pwd
        }
        function getSuffix (filename) {
          let pos = filename.lastIndexOf('.')
          let suffix = ''
          if (pos !== -1) {
            suffix = filename.substring(pos)
          }
          return suffix
        }
        function calculateObjectName (filename) {
          if (gObjectNameType === 'local_name') {
            var __name = gDirname + new Date().getTime() + '__' + filename
            gObjectName = __name
          } else if (gObjectNameType === 'random_name') {
            var suffix = gDirname + getSuffix(filename)
            gObjectName = randomString(10) + suffix
          }
          return ''
        }
        function setUploadParam (up, filename, ret) {
          if (filename !== '') {
            calculateObjectName(filename)
          }
          var newMultipartParams = {
            'key': gObjectName,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'success_action_status': '200', // 让服务端返回200,不然，默认会返回204
            'signature': signature
          }
          let _host = ''
          if (filename.match(/mp4|avi|wmv|mov|FLV/)) {
            _host = host
          } else {
            _host = host2
          }
          up.setOption({
            'url': _host,
            'multipart_params': newMultipartParams
          })
          up.start()
        }
        let uploader = new Plupload.Uploader({
          runtimes: 'html5,flash,silverlight,html4',
          browse_button: 'selectfiles',
          multi_selection: true,
          container: document.getElementById('video_container'),
          flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
          silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
          url: 'http://oss.aliyuncs.com',
          // 文件过滤规则
          filters: {
            mime_types: this.customeType ? [ // 只允许上传视频
              {title: 'Video files', extensions: 'avi,mp4,wmv,mov,FLV,pdf'}
            ] : [
              {title: 'Video files', extensions: 'avi,mp4,wmv,mov,FLV,pdf,jpeg,png,jpg,mp3'}
            ],
            max_file_size: that.maxSize + 'mb', // 最大只能上传3mb的文件
            prevent_duplicates: false // 不允许选取重复文件
          },
          init: {
            PostInit: function () {
              document.getElementById('selectfiles').onclick = function () {
                return false
              }
            },
            FilesAdded: function (up, files) {
              if (files.length > 9) {
                that.$message.warning('最多只能选择9个文件！')
                that.$emit('resetOss')
                return
              }
              that.fileList = []
              that.fileValue = []
              Plupload.each(files, function (file) {
                that.fileList.push({
                  name: file.name,
                  id: file.id,
                  progress: 0,
                  size: Plupload.formatSize(file.size)
                })
              })
              setUploadParam(uploader, '', false)
            },
            BeforeUpload: function (up, file) {
              setUploadParam(up, file.name, true)
            },
            UploadProgress: function (up, file) {
              that.fileList.map(item => {
                if (item.id === file.id) {
                  item.progress = file.percent
                }
              })
            },
            FileUploaded: function (up, file, info) {
              if (info.status === 200) {
                that.fileValue.push(decodeURI(gObjectName))
              } else {
              }
            },
            Error: function (up, err) {
              if (err.code === -600) {
                that.$message.error('视频大小超出限制')
              } else if (err.code === -601) {
                that.$message.error('文件类型不正确')
              } else {
                that.$message.error(err.message)
              }
            }
          }
        })
        uploader.init()
      }
    },
    destroyed () {
      let p = document.getElementsByClassName('file-select')
      for (let i = 0; i < p.length; i++) {
        let t = p[i].getElementsByClassName('video_container')[0]
        if (t) {
          p[i].removeChild(t)
        }
      }
    },
    mounted () {
      this.init()
    }
  }
</script>

<style lang="scss">
.file-upload-wrapper{
  width: 100%;
  .file-content{
    height: 40px;
    line-height: 39px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    padding: 0 15px;
    color: #5a5e66;
    font-size: inherit;
    border-radius: 4px;
    border: 1px solid #d8dce5;
    border-bottom: none;
    .el-icon-close{
      float: right;
      position: relative;
      top: 9px;
      font-size: 18px;
      opacity: 0;
      transition: all 0.2s linear;
      cursor: pointer;
    }
    .el-icon-close:hover{
      color:#409eff;
    }
  }
  .file-content:hover{
    .el-icon-close{
      opacity: 1;
    }
  }
  .file-select{
    -webkit-appearance: none;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #d8dce5;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #5a5e66;
    font-size: inherit;
    height: 40px;
    line-height: 40px;
    outline: 0;
    padding: 0 15px;
    -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    width: 100%;
    text-align: center;
    position: relative;
    input{
      display: block;
      border: none;
      position: absolute;
      width: 100%;
      height: 100%;
      /* background: red; */
      top: 0;
      left: 0;
      opacity: 0;
      cursor: pointer;
    }
  }
}
.file-upload-wrapper.selected{
  .file-content{
    border-radius:0 ;
  }
  .file-content:first-child{
    border-radius: 4px 4px 0 0 ;
  }
  .file-select{
    border-radius: 0 0 4px 4px;
  }
}
.border-bottom:last-child{
  border-bottom: 1px solid #d8dce5;
  border-radius: 0 0 4px 4px !important;
}
</style>
